package dao;

import entity.Blog;
import util.DatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class BlogDao {
    public List<Blog> getHotBlogs(String orderBy) {
        List<Blog> blogs = new ArrayList<>();
        String sql = "SELECT * FROM blog ORDER BY " + orderBy + " DESC LIMIT 10";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(sql);
             ResultSet rs = pst.executeQuery()) {
            while (rs.next()) {
                blogs.add(mapResultSetToBlog(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return blogs;
    }

    public Blog getBlogById(int blogId) {
        String sql = "SELECT * FROM blog WHERE id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setInt(1, blogId);
            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
                return mapResultSetToBlog(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void createBlog(String title, String content, int authorId) {
        String sql = "INSERT INTO blog (title, content, authorId) VALUES (?, ?, ?)";
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement pst = connection.prepareStatement(sql)) {
            pst.setString(1, title);
            pst.setString(2, content);
            pst.setInt(3, authorId);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void updateBlog(String title, String content, int blogId) {
        String sql = "UPDATE blog SET title = ?, content = ? WHERE id = ?";
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement pst = connection.prepareStatement(sql)) {
            pst.setString(1, title);
            pst.setString(2, content);
            pst.setInt(3, blogId);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void deleteBlog(int blogId) {
        String sql = "DELETE FROM blog WHERE id = ?";
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement pst = connection.prepareStatement(sql)) {
            pst.setInt(1, blogId);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void incrementViewCount(int blogId) {
        String updateViewSql = "UPDATE blog SET viewCount = viewCount + 1 WHERE id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(updateViewSql)) {
            pst.setInt(1, blogId);
            pst.executeUpdate();  // 执行更新操作
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean isUserLikedBlog(int userId, int blogId) {
        String sql = "SELECT COUNT(*) FROM `like` WHERE userId = ? AND blogId = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setInt(1, userId);
            pst.setInt(2, blogId);
            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
                return rs.getInt(1) > 0; // 如果返回的计数大于0，表示已点赞
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void likeBlog(int userId, int blogId) {
        String sql = "INSERT INTO `like` (userId, blogId) VALUES (?, ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setInt(1, userId);
            pst.setInt(2, blogId);
            pst.executeUpdate();

            String updateLikeCountSql = "UPDATE blog SET likeCount = likeCount + 1 WHERE id = ?";
            try (PreparedStatement updateStmt = conn.prepareStatement(updateLikeCountSql)) {
                updateStmt.setInt(1, blogId);
                updateStmt.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void unlikeBlog(int userId, int blogId) {
        String sql = "DELETE FROM `like` WHERE userId = ? AND blogId = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setInt(1, userId);
            pst.setInt(2, blogId);
            pst.executeUpdate();

            String updateLikeCountSql = "UPDATE blog SET likeCount = likeCount - 1 WHERE id = ? AND likeCount > 0";
            try (PreparedStatement updateStmt = conn.prepareStatement(updateLikeCountSql)) {
                updateStmt.setInt(1, blogId);
                updateStmt.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public List<Blog> searchBlogsByKeyword(String keyword) {
        List<Blog> blogs = new ArrayList<>();
        String sql = "SELECT * FROM blog WHERE title LIKE ? OR content LIKE ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {

            pst.setString(1, "%" + keyword + "%");
            pst.setString(2, "%" + keyword + "%");
            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                blogs.add(mapResultSetToBlog(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return blogs;
    }

    public List<Blog> getBlogsByAuthorId(int authorId) {
        String sql = "SELECT * FROM blog WHERE authorId = ?";
        List<Blog> blogs = new ArrayList<>();
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setInt(1, authorId);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                blogs.add(mapResultSetToBlog(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return blogs;
    }

    public List<Blog> getBlogsByColumnId(int columnId, String orderBy) {
        List<Blog> blogs = new ArrayList<>();
        String sql = "SELECT * FROM blog WHERE columnId = ? ORDER BY isTop DESC, " + orderBy + " DESC";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setInt(1, columnId);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                blogs.add(mapResultSetToBlog(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return blogs;
    }

    public boolean setTopStatus(int blogId, boolean isTop) {
        String sql = "UPDATE blog SET isTop = ? WHERE id = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setBoolean(1, isTop);
            stmt.setInt(2, blogId);
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public List<Blog> getBlogsWithoutColumn(int userId) {
        List<Blog> blogs = new ArrayList<>();
        String sql = "SELECT * FROM blog WHERE columnId IS NULL AND authorId = ?";  // 查询指定用户没有专栏的博文
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setLong(1, userId);  // 设置用户 ID 参数
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                blogs.add(mapResultSetToBlog(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return blogs;
    }

    public List<Blog> getLikedBlogsByUserId(int userId) {
        List<Blog> likedBlogs = new ArrayList<>();
        String sql = "SELECT blogId FROM `like` WHERE userId = ? AND blogId IS NOT NULL";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, userId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                int blogId = rs.getInt("blogId");
                Blog blog = getBlogById(blogId); // 单独查询每一篇博文
                if (blog != null) {
                    likedBlogs.add(blog);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return likedBlogs;
    }


    private Blog mapResultSetToBlog(ResultSet rs) throws SQLException {
        return new Blog(
                rs.getInt("id"),
                rs.getString("title"),
                rs.getString("content"),
                rs.getInt("authorId"),
                rs.getInt("columnId"),
                rs.getInt("likeCount"),
                rs.getInt("commentCount"),
                rs.getInt("viewCount"),
                rs.getTimestamp("createdTime"),
                rs.getTimestamp("updatedTime"),
                rs.getBoolean("isTop")
        );
    }
}
